import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import devboard.dbutil.MongoUtil;

@WebServlet("/MainHandler")
public class MainHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private enum Reason {
		SAVE_PARAMS{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				InputStreamReader in = new InputStreamReader(request.getInputStream());
				StringBuilder s=new StringBuilder();
				int c;
				while((c=in.read())>=0){
					s.append((char)c);
				}
				in.close();
				DBCollection properties=MongoUtil.getCollection("Properties");
				DBObject property=properties.findOne(new BasicDBObject("_id",(String)request.getSession().getAttribute("_id")));
				String[] temp=s.toString().trim().split("\n");
				for(int i=0;i<temp.length;i++){
					String[] str=temp[i].split("=");
					property.put(str[0], str[1]);
				}
				properties.update(new BasicDBObject("_id",(String)request.getSession().getAttribute("_id")), property);
				return "";
			}
		};
		
		public abstract String processRequest(HttpServletRequest request) throws IOException;
	}
	
    public MainHandler() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Reason reason=Reason.valueOf(request.getParameter("reason"));
		response.getWriter().print(reason.processRequest(request));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Reason reason=Reason.valueOf(request.getParameter("reason"));
		response.getWriter().print(reason.processRequest(request));
	}

}
